package com.example.smartg;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import okhttp3.Call;
import okhttp3.Response;
import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;
import tp.xmaihh.serialport.stick.AbsStickPackageHelper;
import tp.xmaihh.serialport.utils.ByteUtil;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.example.smartg.utils.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class JiJianActivity extends AppCompatActivity {

    public List<Order> historyOrders = new ArrayList<>();
    public LvAdapter lvAdapter;
    private ListView lv;
    public List<Order> orderDetails = new ArrayList<>();
    // 当前格口
    public String currentGe = "";
    public String order = "";
    public int queryFlag = 0;
    String unpacking_command = "";
    // 手动或扫描标致
    public int flag = 0;
    public String openType = "";
    // 串口配置
    public SerialHelper serialHelper;
    public String SPORT_NAME = "/dev/ttyS4"; //串口路径
    // public static String SPORT_NAME = "/dev/ttyUSB2"; //串口路径
    public int BAUD_RATE = 19200; //波特率
    public String error_msg;
    public Dialog dialog;
    public EditText editText;
    public int dialogIsShow = 0;
    private int realOpen = 0;
    //加上计时器
    private Timer mTimer; // 计时器，每2秒执行一次任务
    private MyTimerTask mTimerTask; // 计时任务，判断是否未操作时间到达ns

    /*
     * 串口配置/接收返回的数据
     * （在哪调用这函数都行，只需放在打开串口之前就行了）
     */
    public void initSerialConfig() {
        //初始化SerialHelper对象，设定串口名称和波特率
        serialHelper = new SerialHelper(SPORT_NAME, BAUD_RATE) {
            @Override
            protected void onDataReceived(ComBean paramComBean) {
                Message message = mHandlerJ.obtainMessage();
                message.obj = paramComBean;
                mHandlerJ.sendMessage(message);
            }
        };
        Log.e("Jijian", "initSerialConfig");
        /*
         * 默认的BaseStickPackageHelper将接收的数据扩展成64位，一般用不到这么多位
         * 我这里重新设定一个自适应数据位数的
         */
        serialHelper.setStickPackageHelper(new AbsStickPackageHelper() {
            @Override
            public byte[] execute(InputStream is) {
                try {
                    int available = is.available();
                    if (available > 0) {
                        byte[] buffer = new byte[available];
                        int size = is.read(buffer);
                        if (size > 0) {
                            return buffer;
                        }
                    } else {
                        SystemClock.sleep(50);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
    }

    //接收到的数据
    private Handler mHandlerJ = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            ComBean comBean = (ComBean) msg.obj;
            //获取数据
            String str = ByteUtil.ByteArrToHex(comBean.bRec);
            System.out.println(str);
            // 把电磁锁反馈返回服务器
//            send_feedback_to_server(str);
            // 根据反馈弹出提示框
            return false;
        }
    });

    //打开串口（先配置，再打开串口）
    public boolean openSerialHelper() {
        //已经打开串口了就不用再打开
        if (serialHelper.isOpen()) {
            Log.e("串口状态", "已经打开");
            return false;
        }
        //打开串口
        try {
            serialHelper.open();
            Log.e("串口状态", "打开");
        } catch (IOException e) {
            Log.e("串口状态", "关闭");
            e.printStackTrace();
        }

        return true;
    }

    //关闭串口（注销时候或手动关闭）
    public boolean closeSerialHelper() {
        if (!serialHelper.isOpen()) return false;
        serialHelper.close();
        Log.e("jijian", "serialHelper.close()");
        return true;
    }

    private void open(String cmd_hex) {
        serialHelper.sendHex(cmd_hex); //十六进制数
    }

    public void create_dialog(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.custrom_dialog);
        dialog = builder.create();
    }

    public void showNewChoose(Context context, int big, int mid, int small) {
        if (big + mid + small == 0) {
            ToastUtil.error(JiJianActivity.this, "当前无空闲箱子");
            dialogIsShow = 0;
            dialog.dismiss();
            create_dialog(context);
            return;
        }
        dialogIsShow = 1;
        dialog.show();
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.choose_ge_dialog, null);
//        LvAdapterHistory lvAdapter = new LvAdapterHistory(this, historyOrders)
//        lv = (ListView) v.findViewById(R.id.history_orders);
//        lv.setAdapter(lvAdapter);
//        Button btn_append = (Button) v.findViewById(R.id.append);
        TextView text_big = (TextView) v.findViewById(R.id.big);
        TextView text_mid = (TextView) v.findViewById(R.id.mid);
        TextView text_small = (TextView) v.findViewById(R.id.small);
        ImageButton imageButtonBig = (ImageButton) v.findViewById(R.id.img_big);
        ImageButton imageButtonMid = (ImageButton) v.findViewById(R.id.img_mid);
        ImageButton imageButtonSmall = (ImageButton) v.findViewById(R.id.img_small);
        //        btn_append.setOnClickListener(new View.OnClickListener() {
        //            @Override
        //            public void onClick(View v) {
        //                query_order_info(batch_no,currentGe,"history");
        //            }
        //        });
        text_big.setText("大(" + Integer.toString(big) + ")");
        imageButtonBig.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 新建大格口
                get_unpacking_command("big");
            }
        });
        text_mid.setText("中(" + Integer.toString(mid) + ")");
        imageButtonMid.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 新建中格口
                get_unpacking_command("mid");

            }
        });
        text_small.setText("小(" + Integer.toString(small) + ")");
        imageButtonSmall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 新建小格口
                get_unpacking_command("small");
            }
        });
        Window window = dialog.getWindow();
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        window.setLayout(width, height);
        dialog.getWindow().setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
    }

    public void showHistory(Context context, List<Order> historyOrders, String unpacking_command, String lattice_id, int big, int mid, int small) {
        dialogIsShow = 1;
        dialog.show();
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.choose_ge_dialog_history, null);
        LvAdapterHistory lvAdapter_his = new LvAdapterHistory(this, historyOrders);
        lv = (ListView) v.findViewById(R.id.history_order);
        lv.setAdapter(lvAdapter_his);
        Button btn_append = (Button) v.findViewById(R.id.append);

        btn_append.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 打开历史格口
                currentGe = lattice_id;
                open(unpacking_command);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < historyOrders.size(); i++) {
                            Order order = historyOrders.get(i);
                            orderDetails.add(order);
                        }
//                        Order new_order = new Order();
//                        new_order.index = Integer.toString(historyOrders.size() + 1);
//                        new_order.batch_num = order;
//                        new_order.material_num = "unknow";
//                        new_order.material_quantity = "0";
//                        orderDetails.add(0, new_order);
                        lvAdapter.ge = currentGe;
                        lvAdapter.notifyDataSetChanged();
                    }
                });
                store_item(order);
                dialogIsShow = 0;
                dialog.dismiss();
                create_dialog(JiJianActivity.this);
            }
        });
        Button btn_new = (Button) v.findViewById(R.id.create);
        btn_new.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 让用户选择新格口的类型
                showNewChoose(context, big, mid, small);
            }
        });
        Window window = dialog.getWindow();
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        window.setLayout(width, height);
        dialog.getWindow().setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        dialog.getWindow().setGravity(Gravity.CENTER);//可以设置显示的位置
    }

    public void send_feedback_to_server(String feedback) {
        // 开门成功，反馈成功
        // 开门成功，反馈失败
        // 开门失败，反馈成功
        // 开门失败,反馈失败
        // 关门成功，反馈成功
        // 关门成功，反馈失败
        // 关门失败，反馈成功
        // 关门失败,反馈失败
        // 开门反馈
        // 仅反馈当前门
//        if (feedback.length() < 10 || unpacking_command.length() < 10) {
//            return;
//        }
//        Log.e("276", feedback.substring(2, 6));
//        Log.e("277", unpacking_command.substring(2, 6));
//        if (feedback.substring(2, 6).equals(unpacking_command.substring(2, 6))) {
//            if (feedback.startsWith("8A")) {
//                //开门成功
//                if (feedback.length() == 20) {
//                    if (feedback.substring(16, 18).equals("00")) {
//                        switch_feedback("YS001", currentGe, "开", order);
//                    } else {
//                        currentGe = "";
//                        lvAdapter.ge = "";
//                        ToastUtil.error(JiJianActivity.this, "开门失败");
//                    }
//
//                } else if (feedback.length() == 10) {
//                    if (feedback.substring(6, 8).equals("00")) {
//                        switch_feedback("YS001", currentGe, "开", order);
//                    } else {
//                        currentGe = "";
//                        lvAdapter.ge = "";
//                        ToastUtil.error(JiJianActivity.this, "开门失败");
//                    }
//                }
//            } else if (feedback.startsWith("81")) {
//                Log.e("feedback.substring(6, 8", feedback.substring(6, 8));
//                if (feedback.substring(6, 8).equals("11")) {
//                    //关门成功
//                    switch_feedback("YS001", currentGe, "关", "");
//                    realOpen = 0;
//                } else {
//                    ToastUtil.error(JiJianActivity.this, "关门失败");
//                }
//            }
//        }
        if (feedback.equals("5AA100FB")) {
            ToastUtil.success(JiJianActivity.this, "开门成功1");
        }
    }

    public void switch_feedback(String cabinet_id, String lattice_id, String state, String batch_no) {
        String url = "http://10.2.47.115/smartg_api/deposit_manage/switch_feedback";
        //实例化
        com.example.smartg.HttpUtil httpUtil = new HttpUtil();
        JSONObject json = new JSONObject();
        try {
            json.put("cabinet_id", cabinet_id);
            json.put("lattice_id", lattice_id);
            json.put("state", state);
            json.put("batch_no", batch_no);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("lattice_id", lattice_id);
        Log.e("batch_no", batch_no);
        queryFlag = 1;
        httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //Log.e("exception", e.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        queryFlag = 0;
                        if (state.equals("开")) {
                            currentGe = "";
                            lvAdapter.ge = "";
                            ToastUtil.error(JiJianActivity.this, "服务器异常-1");
                        } else {
                            ToastUtil.error(JiJianActivity.this, "服务器异常-3");
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsedata = response.body().string();
                JSONObject jsonObject = null;
                queryFlag = 0;
                try {
                    jsonObject = new JSONObject(responsedata);
                    String msg = jsonObject.optString("msg");
                    int code = jsonObject.optInt("code");
                    if (code == 20000) {
                        if (state == "开") {
                            // 对话框消失
//                            showToastSuccess("开门成功！");
//                            orderDetails
                            realOpen = 1;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i = 0; i < historyOrders.size(); i++) {
                                        Order order = historyOrders.get(i);
                                        orderDetails.add(order);
                                    }
                                    Order new_order = new Order();
                                    new_order.index = Integer.toString(historyOrders.size() + 1);
                                    new_order.batch_num = order;
                                    new_order.material_num = "unknow";
                                    new_order.material_quantity = "0";
                                    orderDetails.add(0, new_order);
                                    lvAdapter.ge = currentGe;
                                    lvAdapter.notifyDataSetChanged();
                                    Log.e("sssssssss", msg);
                                    ToastUtil.success(JiJianActivity.this, msg);
                                    Log.e("开门", "成功");
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    currentGe = "";
                                    order = "";
                                    historyOrders = new ArrayList<>();
                                    int size = orderDetails.size();
                                    for (int i = 0; i < size; i++) {
                                        orderDetails.remove(0);
                                    }
                                    lvAdapter.ge = "";
                                    lvAdapter.notifyDataSetChanged();
                                }
                            });
                        }
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (state == "开") {
                                    currentGe = "";
                                    lvAdapter.ge = "";
                                    ToastUtil.error(JiJianActivity.this, msg);
                                } else {
                                    ToastUtil.error(JiJianActivity.this, msg);
                                }
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // 首次查询使用
    public void query_order(String batch_no) {
        if (queryFlag == 0) {
            queryFlag = 1;
            //查询申请人存柜情况
            String url = "http://10.2.47.115/smartg_api/deposit_manage/check_applicant_stored";
            //实例化
            com.example.smartg.HttpUtil httpUtil = new HttpUtil();
            JSONObject json = new JSONObject();
            try {
                json.put("cabinet_id", "YS001");
                json.put("batch_no", batch_no);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("exception", e.toString());
                    queryFlag = 0;
                    showToastError(e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    queryFlag = 0;
                    String responsedata = response.body().string();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(responsedata);
                        String msg = jsonObject.optString("msg");
                        int code = jsonObject.optInt("code");
                        if (code == 20000) {
                            // Log.e("接收sucess", msg);
                            // 记录首次扫描的条码
                            order = batch_no;
                            JSONObject data = jsonObject.optJSONObject("data");
                            JSONArray free_lattice_port = data.optJSONArray("free_lattice_port");
                            // 空闲格口数量
                            int big = 0;
                            int mid = 0;
                            int small = 0;
                            for (int i = 0; i < free_lattice_port.length(); i++) {
                                JSONObject item = free_lattice_port.optJSONObject(i);
                                String item_type = item.optString("size");
                                if (item_type.equals("big")) {
                                    big = item.optInt("count");
                                } else if (item_type.equals("mid")) {
                                    mid = item.optInt("count");
                                } else {
                                    small = item.optInt("count");
                                }
                            }
                            final int f_big = big;
                            final int f_mid = mid;
                            final int f_small = small;
                            JSONArray box_info = data.optJSONArray("box_info");
                            String lattice_id = data.optString("_id");
                            currentGe = lattice_id;
                            lvAdapter.ge = lattice_id;
                            if (lattice_id.equals("")) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 没有历史记录，直接弹出让用户选择新建格口类型
                                        showNewChoose(JiJianActivity.this, f_big, f_mid, f_small);
                                    }
                                });

                            } else {
                                // 重置historyOrders
                                int len = historyOrders.size();
                                for (int i = 0; i < len; i++) {
                                    historyOrders.remove(0);
                                }
                                for (int i = 0; i < box_info.length(); i++) {
                                    JSONObject item = box_info.optJSONObject(i);
                                    Order order = new Order();
                                    order.index = Integer.toString(i + 1);
                                    order.batch_num = item.optString("batch_num");
                                    order.material_num = item.optString("material_code");
                                    order.material_quantity = Integer.toString(item.optInt("applicant_num"));
                                    historyOrders.add(order);
                                }
                                unpacking_command = data.optString("unpacking_command");
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 打开有历史记录的对话框
                                        showHistory(JiJianActivity.this, historyOrders, unpacking_command, lattice_id, f_big, f_mid, f_small);
                                    }
                                });
                            }

                        } else {
                            showToastError(msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        showToastError(e.toString());

                    }
                }
            });
        } else {
            ToastUtil.error(this, "查询中,请稍等...");
        }
    }

    // 追加扫描
    public void store_item(String batch_no) {
        if (queryFlag == 0) {
            queryFlag = 1;
            //查询申请人存柜情况
            String url = "http://10.2.47.115/smartg_api/deposit_manage/store_into";
            //实例化
            com.example.smartg.HttpUtil httpUtil = new HttpUtil();
            JSONObject json = new JSONObject();
            try {
                json.put("cabinet_id", "YS001");
                json.put("lattice_id", currentGe);
                json.put("batch_no", batch_no);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("exception", e.toString());
                    queryFlag = 0;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.error(JiJianActivity.this, "服务器异常-5");
                        }
                    });

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    queryFlag = 0;
                    String responsedata = response.body().string();
                    Log.e("res2", responsedata);
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(responsedata);
                        String msg = jsonObject.optString("msg");
                        int code = jsonObject.optInt("code");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (code == 20000) {
                                    // Log.e("接收sucess", msg);
                                    Order order = new Order();
                                    order.index = Integer.toString(orderDetails.size() + 1);
                                    order.batch_num = batch_no;
                                    order.material_quantity = "0";
                                    order.material_num = "unkonw";
                                    orderDetails.add(0, order);
                                    lvAdapter.ge = currentGe;
                                    lvAdapter.notifyDataSetChanged();
                                    ToastUtil.success(JiJianActivity.this, "录入成功！");
                                } else {
                                    ToastUtil.error(JiJianActivity.this, msg);
                                }
                            }
                        });

                    } catch (JSONException e) {
                        e.printStackTrace();
                        showToastError(e.toString());
                    }
                }
            });
        } else {
            ToastUtil.error(this, "查询中,请稍等...");
        }
    }


    public void finish_deposit() {
        if (queryFlag == 0) {
            if(currentGe.isEmpty()){
                ToastUtil.error(this, "当前未开始存件！");
                return;
            }
            queryFlag = 1;
            //查询申请人存柜情况
            String url = "http://10.2.47.115/smartg_api/deposit_manage/finish_deposit";
            //实例化
            com.example.smartg.HttpUtil httpUtil = new HttpUtil();
            JSONObject json = new JSONObject();
            try {
                json.put("lattice_id", currentGe);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("exception", e.toString());
                    queryFlag = 0;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.error(JiJianActivity.this, "服务器异常-5");
                        }
                    });

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    queryFlag = 0;
                    String responsedata = response.body().string();
                    Log.e("res2", responsedata);
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(responsedata);
                        String msg = jsonObject.optString("msg");
                        int code = jsonObject.optInt("code");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (code == 20000) {
                                    // Log.e("接收sucess", msg);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            currentGe = "";
                                            order = "";
                                            historyOrders = new ArrayList<>();
                                            int size = orderDetails.size();
                                            for (int i = 0; i < size; i++) {
                                                orderDetails.remove(0);
                                            }
                                            lvAdapter.ge = "";
                                            lvAdapter.notifyDataSetChanged();
                                            ToastUtil.success(JiJianActivity.this,"已发送邮件通知！");
                                        }
                                    });
                                } else {
                                    ToastUtil.error(JiJianActivity.this, msg);
                                }
                            }
                        });

                    } catch (JSONException e) {
                        e.printStackTrace();
                        showToastError(e.toString());
                    }
                }
            });
        } else {
            ToastUtil.error(this, "请稍等...");
        }
    }

    //获取空闲格口
    public void get_unpacking_command(String size) {
        dialogIsShow = 0;
        dialog.dismiss();
        create_dialog(JiJianActivity.this);
        int length = historyOrders.size();
        for (int i = 0; i < length; i++) {
            historyOrders.remove(0);
        }
        if (queryFlag == 0) {
            queryFlag = 1;
            //查询申请人存柜情况
            String url = "http://10.2.47.115/smartg_api/deposit_manage/get_unpacking_command";
            //实例化
            com.example.smartg.HttpUtil httpUtil = new HttpUtil();
            JSONObject json = new JSONObject();
            try {
                json.put("cabinet_id", "YS001");
                json.put("size", size);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            httpUtil.sendOkHttpRequest(url, json.toString(), new okhttp3.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("exception", e.toString());
                    queryFlag = 0;
//                    ToastUtil.error(JiJianActivity.this,e.toString());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.error(JiJianActivity.this, e.toString());
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    queryFlag = 0;
                    String responsedata = response.body().string();
                    Log.e("res", responsedata);
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(responsedata);
                        String msg = jsonObject.optString("msg");
                        int code = jsonObject.optInt("code");
                        if (code == 20000) {
                            //Log.e("接收sucess", msg);
                            JSONObject data = jsonObject.optJSONObject("data");
                            // 开箱命令
                            unpacking_command = data.optString("unpacking_command");
                            String lattice_id = data.optString("_id");
                            currentGe = lattice_id;
                            lvAdapter.ge = lattice_id;
                            open(unpacking_command);
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    for (int i = 0; i < historyOrders.size(); i++) {
//                                        Order order = historyOrders.get(i);
//                                        orderDetails.add(order);
//                                    }
//                                    Order new_order = new Order();
//                                    new_order.index = Integer.toString(historyOrders.size() + 1);
//                                    new_order.batch_num = order;
//                                    new_order.material_num = "unknow";
//                                    new_order.material_quantity = "0";
//                                    orderDetails.add(0, new_order);
//                                    lvAdapter.ge = currentGe;
//                                    lvAdapter.notifyDataSetChanged();
//                                }
//                            });
                            store_item(order);
                        } else {

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ToastUtil.error(JiJianActivity.this, msg);
                                }
                            });

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtil.error(JiJianActivity.this, e.toString());
                            }
                        });
                    }
                }
            });
        } else {
            ToastUtil.error(this, "查询中,请稍等...");
        }
    }

    @Override
    protected void onPause() {
        Log.e("jijian", "onPause");
        super.onPause();
        stopTimer();
        closeSerialHelper();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ji_jian);
        // 绑定输入框事件
        editText = (EditText) findViewById(R.id.code_num);
        editText.setShowSoftInputOnFocus(true);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                SpUtils.putLong(JiJianActivity.this, "lastActionTime", System.currentTimeMillis());
                if (s.toString().endsWith("\n")) {
                    String result = s.toString().replace("\n", "");
                    if (result.equals("")) {
                        ToastUtil.error(JiJianActivity.this, "条码不允许为空！");
                    } else {
                        currentGe = lvAdapter.ge;
                        if (queryFlag == 0 && dialogIsShow == 0) {
                            if (currentGe.equals("")) {
                                //查询
                                query_order(result);
                            } else {
                                //追加录入
                                store_item(result);
                            }

                        } else {
                            ToastUtil.error(JiJianActivity.this, "查询中，请稍候再试...");
                        }
                    }
                    editText.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        // 绑定按钮事件
        ImageButton return_to_home = (ImageButton) findViewById(R.id.return_to_home);
        return_to_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeSerialHelper();
                finish();
            }
        });
        Button button = (Button) findViewById(R.id.manual_input);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag == 0) {
                    editText.setShowSoftInputOnFocus(false);
                    hideKeyboard(getWindow().getDecorView().getWindowToken());
                    button.setText("扫描输入");
                    flag = 1;
                } else {
                    editText.setShowSoftInputOnFocus(true);
                    button.setText("手动输入");
                    flag = 0;
                }
            }
        });
        lvAdapter = new LvAdapter(this, currentGe, orderDetails);
        lv = (ListView) findViewById(R.id.jijian_details);
        lv.setAdapter(lvAdapter);

        Button store_btn = (Button) findViewById(R.id.store_in);
        store_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish_deposit();
            }
        });

        // 初始化串口
        initSerialConfig();
        openSerialHelper();
        // 创建 dialog
        create_dialog(this);
//        String token = SpUtils.getString(this, "token", "");
//        if (token.equals("")) {
//            Intent intent = new Intent(this, LoginNavActivity.class);
//            startActivity(intent);
//        }
        startTimer();
    }


    // 收起软件键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //如果是点击事件，获取点击的view，并判断是否要收起键盘
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            //获取目前得到焦点的view
            View v = getCurrentFocus();
            //判断是否要收起并进行处理
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        SpUtils.putLong(JiJianActivity.this, "lastActionTime", System.currentTimeMillis());
        //这个是activity的事件分发，一定要有，不然就不会有任何的点击事件了
        return super.dispatchTouchEvent(ev);
    }

    //判断是否要收起键盘
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        //如果目前得到焦点的这个view是editText的话进行判断点击的位置
        if (v instanceof EditText) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            // 点击EditText的事件，忽略它。
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上
        return false;
    }

    //隐藏软键盘并让editText失去焦点
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            //这里先获取InputMethodManager再调用他的方法来关闭软键盘
            //InputMethodManager就是一个管理窗口输入的manager
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (im != null) {
                im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        } else {
            Log.e("xxx", "xxx");
        }
    }

    private void showToastError(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialogIsShow = 0;
                dialog.dismiss();
                create_dialog(JiJianActivity.this);
                ToastUtil.error(JiJianActivity.this, msg);
            }
        });
    }

    private void showToastSuccess(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            }
        });
    }

    @Override
    protected void onDestroy() {
        closeSerialHelper();
        Log.e("jijian", "onDestroy");
        super.onDestroy();
    }

    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            //Log.e(TAG, "计时中……");
            // 1分钟未操作停止计时并退出登录
            TextView tv = (TextView) findViewById(R.id.countdown);
            long mLastActionTime = SpUtils.getLong(JiJianActivity.this, "lastActionTime", 0);
            if ((System.currentTimeMillis() - mLastActionTime - 5000) / 1000 > 0) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(60 - (System.currentTimeMillis() - mLastActionTime - 5000) / 1000 + "秒后退出！！");
                    }
                });
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText("");
                    }
                });
            }
            Log.e("=1=", (System.currentTimeMillis() - mLastActionTime - 5000) / 1000 + "");
            if (System.currentTimeMillis() - mLastActionTime - 5000 > 1000 * 60 * 1) {
                stopTimer();
                SpUtils.clear(JiJianActivity.this);
                dialog.dismiss();
                finish();
            }

        }
    }

    public void stopTimer() {
        Log.e("=1=", "主页定时任务关闭");
        mTimer.cancel();
    }

    private void startTimer() {
        Log.e("=1=", "主页定时任务启动");
        mTimer = new Timer();
        mTimerTask = new MyTimerTask();
        // 初始化上次操作时间为登录成功的时间
        SpUtils.putLong(this, "lastActionTime", System.currentTimeMillis());
        // 每过1s检查一次
        mTimer.schedule(mTimerTask, 0, 1000);
        //Log.e(TAG, "登录成功开始计时");
    }

}

